//index.js
//获取应用实例
const app = getApp();
const util = require('../../utils/util');
const requestUtil = require('../../utils/request');
const api = require('../../config/api');
const common = require('../../utils/common');

Page({
  data: {
    CustomBar: 0,
    hasCardInfo: false, // 是否有卡片信息
    hasGetPhoneNumber: false,
    companyInfo: {}, // 公司信息
    cardInfo: {}, // 卡片信息
    productList: [], // 产品列表数据
    productCardIndex: 0, // 产品推荐滑块索引
    isHome: false,
    swiperList: [{
      id: 0,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big84000.jpg'
    }, {
      id: 1,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big84001.jpg',
    }, {
      id: 2,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big39000.jpg'
    }, {
      id: 3,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg'
    }, {
      id: 4,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big25011.jpg'
    }, {
      id: 5,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big21016.jpg'
    }, {
      id: 6,
      type: 'image',
      url: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big99008.jpg'
    }],
  },

  onLoad: function (options) {
    util.showLoading();
    let cardId = null;
    let userType = null;
    if(options.q) {
        let params = common.getQueryParams(options.q)
        cardId = params.id;
        userType = params.userType;
    }else {
        cardId = options.id;
        userType = options.type ? options.type : options.userType;
    }
    this.setData({
        cardId: cardId,
        userType: userType,
        CustomBar: app.globalData.CustomBar,
        isHome: app.globalData.isHome
    })
    this.getCardInfo(cardId, userType);
    if (!app.globalData.hasCardInfo) {
      app.cardCallback = () => {
        this.onLoadCall();
      };
    } else {
      this.onLoadCall();
    }
  },

  onReady: function () {
    wx.hideLoading();
  },

  onLoadCall: function () {
    if (!app.globalData.hasGetPhoneNumber) {
      this.showModal();
      return;
    }
    this.setData({
      wxType: app.globalData.userType,
    })
    // if (util.isNullOrEmpty(app.globalData.userSig) || util.isNullOrEmpty(app.globalData.adminSig)) {
    //   app.getUserSig();
    // }
    this.addVisit(this.data.cardId);
  },

  getCardInfo: async function (id, userType) {
     
    let _this = this;
    let url;
    if (userType == 1) {
      url = api.urls.queryEmployeeInfo + '/' + id
    } else {
      url = api.urls.queryCustomerInfo + '/' + id
    }
    let res = await requestUtil.request("GET", url, null);
    if (res.data.code != 0) {
      util.showToast(res.data.msg);
      return;
    }
    let data = res.data.data;
    let hasCardInfo = false;
    if (data) {
      hasCardInfo = true;
    }
    let avatarUrl = null;
    if (data.user.headImgUrl != null) {
      avatarUrl = api.picUrl + data.user.headImgUrl;
    }
    let cardInfo = {
      id: data.user.id,
      name: data.user.name,
      position: data.user.position,
      mobile: this.data.userType == 1 ? data.user.mobile : data.user.phone,
      email: data.user.email,
      companyAddr: data.company ? data.company.companyAddr : '',
      companyName: data.company ? data.company.companyName : '',
      wechat: data.user.wxtNo,
      avatar: avatarUrl,
      longitude: data.company ? data.company.longitude : null,
      latitude: data.company ? data.company.latitude : null,
    }
    let companyInfo = data.company.companyInfo;
    data.company.companyInfo = common.formatRichText(common.formatImg(companyInfo));
    
    this.setData({
      cardInfo: cardInfo,
      companyInfo: data.company,
      marker: [{
        id: cardInfo.id,
        latitude: cardInfo.latitude,
        longitude: cardInfo.longitude
      }],
      hasCardInfo: hasCardInfo
    });
  },

  /**
   * 监听转发事件 —— 名片分享
   */
  onShareAppMessage(o) {
    //若是页面的转发
    if (o.from) {
      return {
        title: "您好，这是我的名片。", //转发的标题
        path: '/pages/card/card?id=' + app.globalData.employeeInfo.id +
          '&userType=1'
      };
    }
  },

  // 产品推荐滑动时自动触发
  cardSwiper(e) {
    this.setData({
      productCardIndex: e.detail.current
    })
  },

  //TODO 点击产品时跳转（没做）
  toProductPage: function (e) {
    console.log("toProductPage =>  e  ", e)
  },

  /**
   * 获取企业简介页面信息进行加载
   */
  getPageContent: function () {
    //TODO 没做，直接放上图片吗
  },

  /**
   * 拨打电话 
   */
  callup: function (e) {
    let phone = e.currentTarget.dataset.type;
    if (phone == null) {
      wx.showToast({
        title: '对象未登记手机号',
        icon: 'none'
      })
      return;
    } else {
      wx.makePhoneCall({
        phoneNumber: phone
      })
    }
  },

  /**
   * 导航
   */
  navigateTo: function (o) {
    let address = this.data.cardInfo.companyAddr;
    let latitude = Number(this.data.cardInfo.latitude); // 纬度
    let longitude = Number(this.data.cardInfo.longitude); // 经度
    let name = this.data.cardInfo.companyName;
    let _this = this;
    if (address == null) {
      wx.showToast({
        title: '对象未登记地址',
        icon: 'none'
      })
      return;
    } else {
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: name,
        address: address
      })
    }
  },

  /**
   * 保存到通讯录
   */
  saveCard: function (o) {
    let that = this;
    let cardInfo = this.data.cardInfo;
    wx.addPhoneContact({
      firstName: cardInfo.name,
      photoFilePath: cardInfo.avatar,
      mobilePhoneNumber: cardInfo.mobile,
      weChatNumber: cardInfo.wechat,
      organization: cardInfo.companyName,
      title: cardInfo.position,
      email: cardInfo.email,
      url: cardInfo.link,
      success: () => {
        wx.showToast({
          title: '添加成功',
        })
      },
      fail: (e) => {
        console.log("添加失败，原因为：" + e.errMsg);
      }
    })
  },

  /**
   * 复制到剪切板
   */
  copyData: function (o) {
    let val = o.currentTarget.dataset.val
    wx.setClipboardData({
      data: val
    })
  },

  /**
   * 添加浏览人的数据到缓存或添加到数据库
   * 
   * @param {*} id custid，客户id
   */
  addVisit: function (id) {
    let userType = app.globalData.userType;
    // userType是1，即员工，员工查看历史记录是不需要记录的，所以也包括了自己查看自己的记录不需要再次判断
    if (userType == 1) {
      return;
    }
    // 添加id到缓存
    app.addVisitStorage(id.toString());
    // if (app.globalData.hasGetPhoneNumber) {
    // 直接添加到数据库吧
    common.addVisitIdList([id]);
    // }
  },

  /**
   * 显示获取手机modal
   */
  showModal: function () {
    this.setData({
      modalName: 'GetPhoneModal'
    });
  },

  /**
   * 拒绝获取手机
   */
  rejectModal: function () {
    this.setData({
      reInitToGetPhone: true,
      hasCardInfo: false,
      hasGetPhoneNumber: false
    });
    app.globalData.hasGetPhoneNumber = false;
    this.hideModal();
  },

  /**
   * 隐藏modal
   */
  hideModal: function () {
    this.setData({
      modalName: ''
    });
  },

  /**
   * 获取用户手机号
   */
  getPhoneNumber: async function (e) {
    if (e.detail.errMsg.includes('user deny')) {
      wx.showToast({
        title: '请先使用手机号绑定微信',
        icon: 'none'
      });
      return;
    };
    let _this = this;
    let params = {};
    let sessionKey = wx.getStorageSync('session_key')
    params.sessionkey = sessionKey;
    params.ivdata = e.detail.iv;
    params.encrypdata = e.detail.encryptedData;
    wx.checkSession({
        success: () => {
          _this.getPhone(params);
        },
        fail: () => {
          // session_key过期就重新获取
          _this.reLogin(params, "getPhone");
        }
    })
  },

  /**
   * 获取手机号
   */
  getPhone: async function (params) {
    let _this = this;
    let res = await requestUtil.request("POST", api.urls.getPhone, params);
    if (!res.data) {
      wx.showToast({
        title: '无法获取信息，请重试。',
        icon: 'none'
      })
      _this.setData({
        reInitToGetPhone: false,
      })
      return;
    }
    let phone = res.data.purePhoneNumber; // 没有区号的手机号
    this.bindUser(phone);
  },

  /**
   * openid绑定用户
   */
  bindUser: async function (phone) {
    let openid = wx.getStorageSync('openid');
    if (!openid) {
      this.reLogin(phone, "bindUser");
      return;
    }
    let params = {
      xcxOpenid: openid,
      mobile: phone
    }
    let bindRes = await requestUtil.request("POST", api.urls.bindEmployee, params);
    if (bindRes.data.code != 0) {
      util.showToast(bindRes.data.msg, 'none');
      return;
    }
    util.showToast('绑定成功', 'success');
    app.globalData.phone = phone;
    app.onShow();
    this.hideModal();
  },

  /**
   * login重新获取session_key
   */
  reLogin: function (params, type) {
    let _this = this;
    wx.login({
      success: async function (res) {
        let init = await requestUtil.request("POST", api.urls.initUserInfo, {
          code: res.code
        });
        wx.setStorage({
          key: 'openid',
          data: init.data.data.openid
        });
        wx.setStorage({
          key: "session_key",
          data: init.data.data.session_key
        });
        if (type == "getPhone") {
          params.sessionkey = init.data.data.session_key;
          _this.getPhone(params);
        } else if (type == "bindUser") {
          _this.bindUser(params);
        }
      }
    })
  },

  /**
   * 联系该员工
   */
  contactUser: function () {
    // wx.navigateTo({
    //   url: '../card-center/loginpage/login?id=' + this.data.cardId + '&userType=2',
    // })
    wx.navigateTo({
        url: '../card-create-modify/card-cm?type=3'
    });
  },
})